import ectwitter as twit
import random
import time
import datetime

USER = ""
PASSWORD = ""
RANDOM_HOURS = 3
FIXED_HOURS = 1.5
BEGIN_HOUR = 5
END_HOUR = 17

def go(beginHour, endHour, startNow):
    while (True):
        if (startNow):
            if (time.localtime().tm_hour > beginHour and time.localtime().tm_hour < endHour and datetime.date.today().weekday() < 5):
                tweets = []
                file = open("tweets\pend.txt", "r")
                for line in file:
                    if (line != ""):
                        tweets.append(line)
                file.close()
                cnt = len(tweets)
                if (cnt > 0):
                    rand = random.randint(0, cnt - 1)
                    tweetToSend = tweets[rand]
                    tweets.remove(tweetToSend)
                    wait_seconds = random.randint(0, 60*60*RANDOM_HOURS) + FIXED_HOURS*60*60
                    next_tweet = datetime.datetime.now() + datetime.timedelta(seconds=wait_seconds)
                    twit.set_status(str(tweetToSend), USER, PASSWORD)
                    file = open("tweets\sent.txt", "a")
                    file.write(str(datetime.datetime.now()) + "|" + str(tweetToSend) + str(next_tweet) + "\n")
                    file.close()
    
                    file = open("tweets\pend.txt", "w")
                    for allTweets in tweets:
                        file.write(str(allTweets))
                    file.close()
                time.sleep(wait_seconds)
            else:
                time.sleep(60*5 + random.randint(0, 60*55)) # sleep between 5 and 60 minutes
        else:
            time.sleep(random.randint(0, 60*60*RANDOM_HOURS) + FIXED_HOURS*60*60)

go(BEGIN_HOUR, END_HOUR, True)
